<?php
// 仅当会话尚未启动时调用 session_start()
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查是否为读者角色
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'reader') {
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}

// 数据库连接
$pdo = new PDO('mysql:host=localhost;dbname=library', 'root', '123456');

// 罚金计算函数
function calculateFine($dueDate, $returnDate, $currentDate) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT CalculateFine(:due_date, :return_date, :current_date) AS fine");
    $stmt->bindParam(':due_date', $dueDate);
    $stmt->bindParam(':return_date', $returnDate);
    $stmt->bindParam(':current_date', $currentDate);
    $stmt->execute();
    $fine = $stmt->fetchColumn();
    
    return $fine;
}

// 处理还书逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $book_No = $_POST['book_No'];  // 图书编号
    $u_No = $_SESSION['u_No'];    // 用户编号

    // 检查借阅记录，确保该用户已借出此书且未归还
    $stmt = $pdo->prepare('SELECT * FROM Loan WHERE u_No = ? AND book_No = ? AND (state_ID = "S001" OR state_ID = "S003")');
    $stmt->execute([$u_No, $book_No]);
    $loanRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($loanRecord) {
        // 获取借阅日期
        $loan_date = new DateTime($loanRecord['loan_date']);
        
        // 获取当前日期
        $return_date = new DateTime();

        // 计算借阅日期加一个月后的日期
        $due_date = clone $loan_date;
        $due_date->modify('+1 month');

        // 判断是否逾期
        if ($return_date > $due_date) {
            // 逾期归还
            $state_ID = 'S004';

            // 计算罚金
            $fine = calculateFine($due_date->format('Y-m-d'), $return_date->format('Y-m-d'), $return_date->format('Y-m-d'));
        } else {
            // 正常归还
            $state_ID = 'S002';
            $fine = 0.00;
        }

        // 更新借阅记录为已归还，并设置归还日期
        $stmt = $pdo->prepare('UPDATE Loan SET state_ID = ?, Return_date = ? WHERE Loan_Id = ?');
        $stmt->execute([$state_ID, $return_date->format('Y-m-d'), $loanRecord['Loan_Id']]);

        // 更新 book 表中的 Loan_Id 为 NULL（表示该书已归还）
        $stmt = $pdo->prepare('UPDATE book SET Loan_Id = NULL WHERE book_No = ?');
        $stmt->execute([$book_No]);

        // 提示用户还书成功或逾期
        if ($state_ID === 'S004') {
            echo "<p>逾期归还成功！罚金：￥" . number_format($fine, 2) . "</p>";
        } else {
            echo "<p>正常归还成功！</p>";
        }
    } else {
        echo "<p>未找到借阅记录或图书未借出。</p>";
    }
}

// 获取用户借阅的所有书籍
$u_No = $_SESSION['u_No'];
$stmt = $pdo->prepare('
    SELECT l.book_No, b.B_name, l.loan_date, l.state_ID
    FROM Loan l
    JOIN book b ON l.book_No = b.book_No
    WHERE l.u_No = ? AND (l.state_ID = "S001" OR l.state_ID = "S003")
');
$stmt->execute([$u_No]);
$borrowedBooks = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>还书</title>
    <style>
      
       
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        table th, table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        table th {
            background-color: #f4f4f4;
        }
        .return-button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        .return-button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <div >
        <h2>还书</h2>
        <table>
            <thead>
                <tr>
                    <th>图书编号</th>
                    <th>书名</th>
                    <th>借阅日期</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($borrowedBooks): ?>
                    <?php foreach ($borrowedBooks as $book): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($book['book_No']); ?></td>
                            <td><?php echo htmlspecialchars($book['B_name']); ?></td>
                            <td><?php echo htmlspecialchars($book['loan_date']); ?></td>
                            <td><?php echo $book['state_ID'] === 'S001' ? '借出中' : '续借中'; ?></td>
                            <td>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="book_No" value="<?php echo htmlspecialchars($book['book_No']); ?>">
                                    <button type="submit" class="return-button">还书</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="5">暂无借阅中的图书。</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</body>
</html>
